<template>
    <BasicInformation :title="title" @action="handleAction" :primary-actions="mainActions"></BasicInformation>
    <div class="add">
       <div class="common-layout">
         <el-container>
           <el-main>
             <el-row>
               <el-col :span="24">
                 <div class="grid-content ep-bg-purple">
                   <h4>基本信息</h4>
                   <el-form :inline="true" :model="salesCollectionRefund" :rules="rules" status-icon ref="formRef">
                     <el-form-item label="单据编号" prop="docCode">
                 <el-input
                     v-model="salesCollectionRefund.docCode"
                     style="width: 240px"
                     placeholder="请输入单据编号"
                     clearable
                     :disabled="true"
                     />
                         </el-form-item>
                     <!-- 客户 -->
                     <el-form-item label="客户" prop="cid">
                             <el-select
                               v-model="salesCollectionRefund.cid"
                               placeholder="请选择客户"
                               style="width: 240px"
                               clearable
                               filterable
                             >
                               <el-option
                                 v-for="customer in customerList"
                                 :key="customer.id"
                                 :label="`${customer.code} - ${customer.name}`"
                                 :value="customer.id"
                               />
                             </el-select>
                           </el-form-item>

                     <!-- 报价日期 -->
                     <el-form-item label="单据日期" prop="docDate">
                       <el-date-picker
                         v-model="salesCollectionRefund.docDate"
                         type="date"
                         placeholder="请选择日期"
                         value-format="YYYY-MM-DD"
                         :disabled-date="disabledDate"
                       />
                     </el-form-item>
                     <!-- 业务员 -->
                      <el-form-item label="业务员" prop="uid">
                                            <el-select v-model="salesCollectionRefund.uid" placeholder="请选择业务员" clearable filterable @change="" style="width: 240px;">
                                            <el-option v-for="item in userList"
                                            :key="item.id"
                                            :label="item.name"
                                            :value="item.id">
                                            </el-option>
                                            </el-select>                                                                     
                                        </el-form-item>

                     
                     <!-- 部门 -->
                        <el-form-item label="部门" prop="did">
                                            <el-select
                                                v-model="AddSalesAdvanceRefund.did"
                                                placeholder="请选择部门"
                                                style="width: 240px;"
                                                clearable
                                            >
                                                <el-option
                                                    v-for="dept in deptList"
                                                    :key="dept.id"
                                                    :label="dept.name"
                                                    :value="dept.id"
                                                />
                                            </el-select>
                                     </el-form-item>

                                         <el-form-item label="单据备注" prop="notes">
                                                <el-input 
                                                v-model="AddSalesAdvanceRefund.notes"
                                                style="width: 240px"
                                                placeholder="请输入单据备注"
                                                clearable
                                                />
                                        </el-form-item>
                   </el-form>
                 </div>
               </el-col>
             </el-row>
           </el-main>
         </el-container>
       </div>
     </div>
   <!-- 退款信息表格 -->
  <div class="collection-info">
    <h4>退款信息</h4>
    <el-table :data="paymentAccounts" border style="width: 100%">
      <el-table-column label="退款账户" align="center" width="150">
        <template #default="scope">
          <el-select
            v-model="scope.row.accountName"
            placeholder="请选择账户"
            clearable
          >
            <el-option
              v-for="account in payAccountList"
              :key="account.id"
              :label="account.account"
              :value="account.id"
            />
          </el-select>
        </template>
      </el-table-column>

      <el-table-column label="退款方式" align="center" width="150">
        <template #default="scope">
          <el-select
            v-model="scope.row.paymentMethod"
            placeholder="请选择方式"
            clearable
          >
            <el-option
              v-for="method in payIdList"
              :key="method.id"
              :label="method.payName"
              :value="method.id"
            />
          </el-select>
        </template>
      </el-table-column>

      <el-table-column label="退款金额" align="center" width="180">
        <template #default="scope">
          <el-input-number
            v-model="scope.row.amount"
            :min="0"
            :precision="2"
            controls-position="right"
            style="width: 160px"
          />
        </template>
      </el-table-column>

      <el-table-column label="手续费" align="center" width="150">
        <template #default="scope">
          <el-input-number
            v-model="scope.row.fee"
            :min="0"
            :precision="2"
            controls-position="right"
            style="width: 120px"
          />
        </template>
      </el-table-column>

      <el-table-column label="交易号/票据号" align="center">
        <template #default="scope">
          <el-input
            v-model="scope.row.transactionNo"
            placeholder="请输入交易号"
            clearable
          />
        </template>
      </el-table-column>

      <el-table-column label="退款备注" align="center">
        <template #default="scope">
          <el-input
            v-model="scope.row.remark"
            placeholder="请输入备注"
            clearable
          />
        </template>
      </el-table-column>
    </el-table>
    <div class="validation-info">
    <el-alert
      v-if="netCollectionAmount > maxSettleAmount"
      type="error"
      :closable="false"
      show-icon
    >
      超额退款！可核销上限：¥{{ maxSettleAmount.toFixed(2) }}
    </el-alert>

    <div class="amount-summary">
      <span>净退款金额：¥{{ netCollectionAmount.toFixed(2) }}</span>
      <span style="margin-left: 20px">已核销金额：¥{{ totalCurrentSettle.toFixed(2) }}</span>
    </div>
  </div>

  <!-- 修改确定按钮事件处理 -->
  <el-button
    type="primary"
    @click="confirmSelection"
    :disabled="totalCurrentSettle >= maxSettleAmount"
  >
    确定（剩余可核销：¥{{ (maxSettleAmount - totalCurrentSettle).toFixed(2) }}）
  </el-button>


    <div class="total-summary">
      <div class="total-label">收款合计</div>
      <div class="total-amount">{{ formatPaymentTotal }}</div>
    </div>
  </div>

  <!-- 源单信息表格 -->
  <div class="source-info">
    <div class="toolbar">
      <el-button type="primary" @click="selectSourceOrder">选择源单</el-button>
      <el-button type="warning" @click="autoSettled">自动核销</el-button>
    </div>

    <el-table :data="sourceOrders" border style="width: 100%">
      <el-table-column label="源单日期" align="center" width="120">
        <template #default="scope">{{ scope.row.orderDate }}</template>
      </el-table-column>

      <el-table-column label="源单类型" align="center" width="120">
        <template #default="scope">{{ scope.row.orderType }}</template>
      </el-table-column>

      <el-table-column label="源单编号" align="center" width="180">
        <template #default="scope">{{ scope.row.orderCode }}</template>
      </el-table-column>

      <el-table-column label="客户名称" align="center" width="150">
        <template #default="scope">{{ scope.row.customerName }}</template>
      </el-table-column>
      <el-table-column label="已核销金额" align="center" width="120">
        <template #default="scope">¥{{ scope.row.settledAmount.toFixed(2) }}</template>
      </el-table-column>

      <el-table-column label="未核销金额" align="center" width="120">
        <template #default="scope">¥{{ (scope.row.totalAmount - scope.row.settledAmount).toFixed(2) }}</template>
      </el-table-column>

      <el-table-column label="本次核销" align="center" width="150">
        <template #default="scope">
          <el-input-number
            v-model="scope.row.currentSettle"
            :min="0"
            :max="scope.row.totalAmount - scope.row.settledAmount"
            :precision="2"
            controls-position="right"
            style="width: 120px"
          />
        </template>
      </el-table-column>

      <el-table-column label="操作" align="center" width="80">
        <template #default="scope">
          <el-button link type="danger" @click="removeSourceOrder(scope.row)">移除</el-button>
        </template>
      </el-table-column>
    </el-table>
  </div>


   <el-dialog
   v-model="dialogVisible"
   title="销售出库单"
   width="80%"
   top="5vh"
 >
   <!-- 查询条件区域 -->
   <div class="dialog-header">
     <el-input
       v-model="searchForm.code"
       placeholder="请输入单据编号"
       style="width: 240px;margin-right: 15px"
     />
     <span class="date-label">单据日期：</span>
     <el-date-picker
       v-model="searchForm.startDate"
       type="date"
       placeholder="开始日期"
       value-format="YYYY-MM-DD"
       style="width: 160px"
     />
     <span class="date-separator">~</span>
     <el-date-picker
       v-model="searchForm.endDate"
       type="date"
       placeholder="结束日期"
       value-format="YYYY-MM-DD"
       style="width: 160px;margin-right: 15px"
     />
     <el-button type="primary" icon="Search" @click="searchSalesCollection">查询</el-button>
     <el-button icon="Refresh" @click="resetSearch">重置</el-button>
     <el-button icon="ArrowDown">展开</el-button>
   </div>

   <!-- 选择状态提示 -->
   <div class="selected-info">
     <span>已选择{{ selectedCount }}项</span>
     <el-button link type="primary" @click="clearSelection">清空</el-button>
   </div>

   <!-- 表格区域 -->
   <el-table
     :data="salesCollectionList"
     border
     height="60vh"
     @selection-change="handleSelectionChange"

   >
     <el-table-column type="selection" width="55" align="center" />
     <el-table-column prop="docCode" label="单据编号" width="180" />
     <el-table-column prop="docDate" label="单据日期" width="120" />
     <el-table-column prop="notes" label="单据主题" width="200" />
     <el-table-column prop="cid" label="客户" width="120" />
     <el-table-column prop="did" label="业务部门" width="120" />
     <el-table-column prop="uid" label="业务员" width="120" />
     <el-table-column prop="closed" label="已关闭" width="100" align="center">
       <template #default="scope">
         <el-tag :type="scope.row.closed ? 'danger' : 'success'" size="small">
           {{ scope.row.closed ? '是' : '否' }}
         </el-tag>
       </template>
     </el-table-column>
   </el-table>

   <!-- 分页及操作按钮 -->
   <div class="dialog-footer">
      <!-- 分页组件 -->
      <div class="pagination-wrapper">
             <el-pagination
                 background
                 layout="prev, pager, next"
                 :total="totalItems"
                 :page-size="PopupsPageSize"
                 :current-page="PopupsPageNo"
                 @current-change="handlePageChange"
             />
         </div>
     <div class="action-buttons">
       <el-button @click="dialogVisible = false">关闭</el-button>
       <el-button type="primary" @click="confirmSelection">确定</el-button>
     </div>
   </div>
 </el-dialog>



 </template>


 <script setup lang="ts">
 import { ref, reactive,withKeys ,watch,computed, onMounted} from 'vue';
 import BasicInformation from '@/public-view/BasicInformation.vue';
 import type {ComponentSize, FormInstance, FormRules} from 'element-plus'
 import {ElInput, ElAutoResizer, ElTableV2} from 'element-plus'
 import type {FunctionalComponent} from 'vue'
 import type {Column, InputInstance} from 'element-plus'
 import { useRouter,useRoute } from 'vue-router';
 import type { Customer } from '@/types/public-xs/Customer';
 import axios from 'axios';
 import { ElMessageBox, ElMessage } from 'element-plus'
 import type { SalesCollection,SalesCollectiondetail,SalesOut,SalesOutDetail,SalesCollectionRefund,SalesCollectionRefunddetail} from '@/types/public-xs/salesDocuments';
 import request from '@/util/request'
import AddSalesAdvanceRefund from './AddSalesAdvanceRefund.vue';
import type { User } from '@/types/rs/User';
import type { Department } from '@/types/rs/Department';
import type { PayAccount } from '@/types/cw/Public';
import type { PaymentMethod } from '@/types/public-xs/CwOtherIncome';

 let docCode=ref('')
 let sourceSheet=ref('')
 let title=ref('收款退款单')
 let pageNo=ref(1)
 let pageSize=ref(5)
 let allPage=ref(0)
 let router=useRouter()

 //销售收款单
let salesCollection=ref<SalesCollection>({
    id: 0,
    docCode: 'string',
    docDate:new Date,
    cid: null,
    uid: 0,
    collectionAmount: 0,//收款金额
    sourceSheet:'',
    details:[],
    status: -1,
    notes: '',
    createBy: '',
    createTime:new Date,
    updateBy: '毕建峰',
    updateTime:new Date,
    isDelete: 0,
    did: 0,
    settledTotalAmount: 0,
    typeId:15
})
let salesCollectionRefunddetailList=ref<SalesCollectionRefunddetail[]>([])
//销售收款退款单对象
let salesCollectionRefund=ref<SalesCollectionRefund>({
    id:0,
    docDate:new Date,
    docCode: 'string',
    status: 0,
    cid: null,
    refundAmount: 0,
    verRefundAmount: 0,
    refundAccount: 'string',
    refundWay: 'string',
    uid: 1,
    createBy: 'string',
    createTime: new Date,
    updateBy: 'string',
    updateTime:new Date,
    did: 1,
    isDelete: 0,
    details: salesCollectionRefunddetailList.value,
    typeId:16

})






 //部门情况
 const departments = ref([
   { value: 1, label: '销售部' },
   { value: 2, label: '技术部' },
   { value: 3, label: '财务部' }
 ])
 //商品查询条件
 const queryConditions = reactive({
   combine: '',
   kid: ''
 })
const rules = reactive<FormRules>({
  cid: [
    { 
      required: true, 
      message: '必须选择客户', 
      trigger: ['blur', 'change'],
      type: 'number'
    }
  ],
  docDate: [
    { 
      required: true, 
      message: '必须选择单据日期', 
      trigger: 'change',
      validator: (_, value) => {
        if (!value) return false
        const selectedDate = new Date(value)
        const today = new Date()
        today.setHours(0,0,0,0)
        return selectedDate > today ? '不能选择未来日期' : true
      }
    }
  ],
  uid: [
    { 
      required: true, 
      message: '必须选择业务员', 
      trigger: 'change',
      type: 'number' 
    }
  ],
  did: [
    { 
      required: true, 
      message: '必须选择部门', 
      trigger: 'change',
      type: 'number'
    }
  ]
})

const tableRules = reactive({
  accountName: [{
    required: true,
    message: '必须选择退款账户',
    trigger: ['blur', 'change']
  }],
  paymentMethod: [{
    required: true,
    message: '必须选择退款方式',
    trigger: ['blur', 'change']
  }],
  amount: [
    { 
      required: true,
      message: '必须填写退款金额',
      trigger: ['blur', 'change']
    },
    { 
      type: 'number',
      min: 0.01,
      message: '金额需大于0',
      trigger: ['blur', 'change']
    }
  ],
  fee: [
    { 
      validator: (_:any, val:number, row:any) => 
      val > row.amount ? '手续费不能超过退款金额' : true,
      trigger: ['blur', 'change']
    }
  ],
  transactionNo: [
    { 
      validator: (_:any, val:number, row:any) => {
        if (['银行转账', '支票'].includes(row.paymentMethod) && !val) {
          return '该支付方式必须填写交易号'
        }
        return true
      },
      trigger: ['blur', 'change']
    }
  ]
})
const formRef = ref<FormInstance>()
const validateAll = async () => {
  try {
    // 1. 主表单校验
    await formRef.value?.validate()

    // 2. 退款表格校验
    const tableValidations = paymentAccounts.value.map((_, index) => 
      formRef.value?.validateField([
        `paymentAccounts.${index}.accountName`,
        `paymentAccounts.${index}.paymentMethod`,
        `paymentAccounts.${index}.amount`
      ])
    )
    await Promise.all(tableValidations)

    // 3. 源单核销校验
    const sourceValidations = sourceOrders.value.map((_, index) =>
      formRef.value?.validateField(`sourceOrders.${index}.currentSettle`)
    )
    await Promise.all(sourceValidations)

   

    return true
  } catch (error) {
    ElMessage.error('存在未通过的校验项')
    return false
  }
}


 const disabledDate = (time: Date) => {
     return time.getTime() > Date.now()
 }
 // 修改handleAction方法
 const handleAction = (action:string) => {
   switch(action) {
     case 'choose':
       if (!salesCollectionRefund.value.cid) {
         ElMessage.warning('请先选择客户')
         return
       }
       dialogVisible.value = true
        // 自动触发数据加载
        searchSalesCollection()
       break
     case 'save-add':
     insertSalesClo()
       break;
     case 'history':
       router.push('/home/salesCollectionRefund')
       break;



   }
 }

 const mainActions = ref([
   {
     name: 'save',
     label: '保存',
     type: 'primary',
     icon: 'DocumentAdd'
   },
   {
     name: 'save-add',
     label: '保存新增',
     disabled: false
   },
   {
     name: 'audit',
     label: '审核',
     hidden: false
   },
   {
     name: 'choose',
     label: '选择源单',
     hidden: false
   },
   {
     name: 'history',
     label: '历史单据',
     badge: 3 // 角标数字
   }
 ])



 //访问方法并获取单据编号
 let getDocCode=async()=>{
   let response=await request.post('/xs/counter/addCode',{docType:'SKTKD'})
   docCode.value=response.data.data
   salesCollectionRefund.value.docCode=docCode.value
 }

 onMounted(async () => {
   await getDocCode()
 })

 // todo
 const generateUUID = () => {
     return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, (c) => {
     const r = (Math.random() * 16) | 0
     const v = c === 'x' ? r : (r & 0x3) | 0x8
     return v.toString(16)
   })
 }
 //动态加载客户
let customerList = ref<Customer[]>([])
let selectCustomer = async () => {
    let response = await request.post('/basic/Customer/selectAllCustomer')
    customerList.value = response.data.data
    console.log(customerList.value)

}
selectCustomer()

 let userList=ref<User[]>([])
 let selectUser=async()=>{
  let response=await  request.post('/per/user/getAll')
  userList.value=response.data.data
  console.log(userList.value)
}
selectUser()

let deptList=ref<Department[]>([])
let selectDept=async()=>{
  let response=await  request.post('/per/dept/getAll')
  deptList.value=response.data.data
  console.log(deptList.value)
}
selectDept()

let payAccountList = ref<PayAccount[]>([])
let  selectAllBankAccount=async()=>{
  let accountRes = await request.post("basic/Account/selectAllAccount")
  payAccountList.value = accountRes.data.data
}
selectAllBankAccount()


 const tableData = ref([{
   id: generateUUID(),
   goodId:0,
   code: '',
   name:'',
   quantity: 1,
   actualPrice: 0,
   returnReason: '',
   tax: 13,
   taxIncludedPrice: 0,
   stock:100,
   unit: '件',
   kname:'测试',
   returnQuantity:0
 }])


   //获取到付款方式的方法
 let payIdList=ref<PaymentMethod[]>([])
 let selectpayId=async()=>{
  let response=await request.post("/cw/PaymentMethodController/selectPaymentMethod")
   payIdList.value=response.data.data
   console.log(payIdList.value)
 }
selectpayId()

 const newSelectedRows = ref<any[]>([])

 // 处理选中行变化
 const newHHandleSelectionChange = (selection: any[]) => {
   newSelectedRows.value = selection
 }

 // 删除选中行方法（添加确认对话框）
 const deleteSelectedRows = async () => {
   if (newSelectedRows.value.length === 0) {
     ElMessage.warning('请先选择要删除的行')
     return
   }

   try {
     await ElMessageBox.confirm(
       `确定要删除选中的 ${newSelectedRows.value.length} 行吗？`,
       '删除确认',
       {
         confirmButtonText: '确定',
         cancelButtonText: '取消',
         type: 'warning'
       }
     )
     // 通过ID过滤实现删除
     const selectedIds = new Set(newSelectedRows.value.map(row => row.id))
     tableData.value = tableData.value.filter(row => !selectedIds.has(row.id))
     ElMessage.success('删除成功')
   } catch (error) {
     ElMessage.info('已取消删除')
   }
 }


 //价格校验
 const validatePrice = (row:any) => {
   row.actualPrice = row.actualPrice.replace(/[^\d.]/g, '')
 }

 // 含税价计算
 const calculateTaxPrice = (row:any) => {
   if (row.actualPrice && row.vatRate) {
     row.taxIncludedPrice = (row.actualPrice * (1 + row.vatRate/100)).toFixed(2)
   }
 }

 //只读队列
 const readonlyColumns = [
   { prop: 'kname', label: '商品种类', width: 120 },
   { prop: 'suggestedPrice', label: '建议报价', width: 120 },
   { prop: 'taxIncludedPrice', label: '含税单价', width: 120 },
   { prop: 'tax', label: '增值税税率 (%)', width: 150 }
 ]
 // 显示历史报价
 const showHistory = (row:any) => {
   console.log('显示历史报价:', row.goodsCode)
   // 实际应调用API获取历史数据
 }
 //格式化金额显示
 const totalAmount = computed(() => {
   return tableData.value.reduce((sum, row) => {
     const price = Number(row.actualPrice) || 0
     const qty = Number(row.returnQuantity) || 0 // 关键修改点
     return sum + (price * qty)
   }, 0)
 })
 const formatTotal = computed(() => {
   return `¥${totalAmount.value.toFixed(2)}`
 })
 let PopupsPageNo=ref(1)
 let PopupsPageSize=ref(10)
 const selectedCount = ref(0)
 const totalItems = ref(0)
 const dialogVisible = ref(false)
 const currentSelected =ref<SalesCollection|null>()
 const selectedRows =ref<SalesCollection[]>([])
 const searchForm = reactive({
     code: '',
   startDate: '',
   endDate: ''
 })
 // 表格选择处理
 const handleSelectionChange = (selection:any) => {
   selectedRows.value = selection
   selectedCount.value = selection.length
   if (selection.length > 0) {
     currentSelected.value = selection[0]
   } else {
     currentSelected.value = null
   }
 }
 const clearSelection = () => {

 }

 //分页方法
 let handlePageChange=()=>{

 }
 let salesCollectionList=ref<SalesCollection[]>([])
 // 获取源单数据
 const searchSalesCollection = async () => {
   try {
     const params = {
       code: searchForm.code,
       startDate: searchForm.startDate,
       endDate: searchForm.endDate,
       pageNo: PopupsPageNo.value,
       pageSize: PopupsPageSize.value,
       cid:salesCollectionRefund.value.cid
     }
     const res = await request.post('/cw/SalesCollectionController/selectSalesCollectionByPage', params)
     salesCollectionList.value = res.data.data.list
     totalItems.value = res.data.data.total
   } catch (error) {
     console.error('查询失败:', error)
   }
 }
 const resetSearch = () => {
   searchForm.code = ''
   searchForm.startDate = ''
   searchForm.endDate = ''
   searchSalesCollection()
 }

 const confirmSelection = async() => {
  if (selectedRows.value.length === 0) {
    ElMessage.warning('请至少选择一条源单单')
    return
  }
  const newSourceOrders = selectedRows.value.map(row => ({
  orderId: row.id,
  orderDate: row.createTime,
  orderType: '收款单', // 根据类型值转换文本
  orderCode: row.docCode,
  customerName: customerList.value.find(c => c.id === row.cid)?.name,
  totalAmount: row.collectionAmount,
  settledAmount: 0, // 调用接口获取已核销金额
  currentSettle: 0 // 初始化本次核销金额
}));

  const existingIds = new Set(sourceOrders.value.map(o => o.orderId))
  const validOrders = newSourceOrders.filter(o => !existingIds.has(o.orderId))

  // 添加新订单
  sourceOrders.value = [...sourceOrders.value, ...validOrders]

  // 关闭对话框并重置选择
  dialogVisible.value = false
  selectedRows.value = []
  selectedCount.value = 0
  ElMessage.success(`成功添加${validOrders.length}条源单`)

 }

 const generateDetails = () => {
  return paymentAccounts.value.map(order => ({
    id: 0,
    mainCode: salesCollectionRefund.value.docCode,
    refundName: 'string',
    refundAmount: order.amount,
    verAmount: 0,
    taxRate: 0,
    taxAmount: 0,
    notes: 'string',
    createTime: new Date,
    updateTime: new Date,
    sourceSheet:  '',
    createBy: 'String',
    updateBy: 'String',
    refundAccount:order.accountName,
    refundWay:order.paymentMethod,
    isDelete:0

  })) as SalesCollectionRefunddetail[];
};


 const paymentAccounts = ref([
  {
    id: 1,
    accountName: 1,
    paymentMethod:1,
    amount: 0,
    fee: 0,
    transactionNo: '',
    remark: ''
  }
])



const paymentMethods = ref([
  { value: '银行转账', label: '银行转账' },
  { value: '支付宝', label: '支付宝' },
  { value: '微信支付', label: '微信支付' }
])

// 新增源单信息相关数据
const sourceOrders = ref<any[]>([])
const sourceDialogVisible = ref(false)

// 计算属性
const formatPaymentTotal = computed(() => {
  const total = paymentAccounts.value.reduce(
    (sum, row) => sum + Number(row.amount) - Number(row.fee),
    0
  )
  return `¥${total.toFixed(2)}`
})

// 新增方法
const selectSourceOrder = () => {
  sourceDialogVisible.value = true
  // 这里可以调用加载源单数据的方法
}

const autoSettled = async () => {
  try {
    const netAmount = netCollectionAmount.value
    if (netAmount <= 0) {
      ElMessage.warning('请先填写有效的收款金额')
      return
    }

    // 计算可分配总额
    let remaining = netAmount
    sourceOrders.value = sourceOrders.value.map(order => {
      const max = order.totalAmount - order.settledAmount
      const allocatable = Math.min(max, remaining)
      order.currentSettle = allocatable
      remaining -= allocatable
      return order
    })

    if (remaining > 0) {
      ElMessage.warning(`自动核销后仍有 ¥${remaining.toFixed(2)} 未分配`)
    }
  } catch (error:any) {
    ElMessage.error('自动核销失败：' + error.message)
  }
}

const removeSourceOrder = (row: any) => {
  sourceOrders.value = sourceOrders.value.filter(item => item.orderId !== row.orderId)
}

const totalSettledAmount = computed(() => {
  return sourceOrders.value.reduce((sum, order) =>
    sum + (order.currentSettle || 0), 0)
});

// 监听器更新主单收款金额
watch(totalSettledAmount, (newVal) => {
  salesCollection.value.collectionAmount = newVal;
});
const validateSettlement = () => {
  if (netCollectionAmount.value > maxSettleAmount.value) {
    ElMessage.error(`收款金额不可超过可核销总额 ¥${maxSettleAmount.value.toFixed(2)}`)
    return false
  }

  // 规则2：核销总金额必须等于净收款金额
  if (Math.abs(totalCurrentSettle.value - netCollectionAmount.value) > 0.01) {
    ElMessage.error('核销总金额与净收款金额不匹配')
    return false
  }


  return sourceOrders.value.every(order => {
    const maxAmount = order.totalAmount - order.settledAmount;
    return order.currentSettle > 0 && order.currentSettle <= maxAmount;
  });
};
const maxSettleAmount = computed(() => {
  return sourceOrders.value.reduce((sum, order) => {
    return sum + (order.totalAmount - order.settledAmount)
  }, 0)
})

// 计算实际可用收款金额（总收款金额 - 总手续费）
const netCollectionAmount = computed(() => {
  return paymentAccounts.value.reduce((sum, row) =>
    sum + (Number(row.amount) || 0) - (Number(row.fee) || 0)
  , 0)
})

// 计算当前核销总金额
const totalCurrentSettle = computed(() => {
  return sourceOrders.value.reduce((sum, order) =>
    sum + (Number(order.currentSettle) || 0)
  , 0)
})



 //点击新增后新增收款单
 let insertSalesClo =async()=>{
  if (!validateSettlement()) {
    ElMessage.error('存在非法核销金额，请检查源单可核销额度');
    return;
  }
   if (!await validateAll()) return

  // 构造明细数据
  const details = generateDetails()
  salesCollectionRefund.value.refundAmount = totalSettledAmount.value;
  salesCollectionRefund.value.verRefundAmount = totalSettledAmount.value;
  // 更新主单收款总额
    let response=await request.post("/cw/SalesCollectionRefundController/insertSalesCollectionRefund",{
      salesCollectionRefund:salesCollectionRefund.value,
      details:details
    })
    if(response.data.code=='200'){
      ElMessage.success("退款成功")
      router.push("/home/salesCollectionRefund")
    }else{
      ElMessage.error("退款失败")
    }
 }

 </script>


 <style scoped>
 .el-row {
     margin-bottom: 20px;
 }

 .el-row:last-child {
     margin-bottom: 0;
 }

 .el-col {
     border-radius: 4px;
 }

 .grid-content {
     border-radius: 4px;
     min-height: 36px;
 }
 .required-label::after {
   content: "*";
   color: #f56c6c;
   margin-left: 4px;
 }

 .goods-table {
   margin-top: 20px;
 }

 .toolbar {
   margin-bottom: 15px;
   padding: 10px;
   background: #f5f7fa;
   border-radius: 4px;
 }

 .el-table :deep(.el-input__inner) {
   text-align: center;
 }
 .total-summary {
   background: #fff8dc; /* 浅黄色背景 */
   padding: 12px 20px;
   display: flex;
   justify-content: flex-end;
   border: 1px solid #ebeef5;
   border-top: none;
 }

 .total-label {
   font-weight: 600;
   color: #606266;
   margin-right: 30px;
 }

 .total-amount {
   color: #f56c6c;
   min-width: 120px;
   text-align: right;
   font-family: Arial, sans-serif;
 }
 .pagination-wrapper {
     margin-top: 16px;
     display: flex;
     justify-content: flex-end;
 }
 .dialog-header {
   display: flex;
   align-items: center;
   margin-bottom: 15px;
   flex-wrap: wrap;
   gap: 10px;
 }

 .date-label {
   color: #606266;
   margin: 0 10px;
 }

 .date-separator {
   margin: 0 8px;
   color: #c0c4cc;
 }

 .selected-info {
   margin: 12px 0;
   display: flex;
   align-items: center;
   gap: 10px;
   color: #606266;
 }

 .dialog-footer {
   display: flex;
   justify-content: space-between;
   align-items: center;
   margin-top: 15px;
 }

 .pagination-info {
   color: #606266;
 }

 .action-buttons {
   display: flex;
   gap: 15px;
 }

 :deep(.el-dialog__header) {
   border-bottom: 1px solid #ebeef5;
 }

 .collection-info {
  margin: 20px 0;
  padding: 15px;
  background: #f8f9fa;
  border-radius: 4px;
}

.source-info {
  margin-top: 20px;
  border-top: 2px solid #ebeef5;
  padding-top: 15px;
}

.toolbar {
  margin-bottom: 15px;
}

.total-summary {
  display: flex;
  justify-content: flex-end;
  align-items: center;
  margin-top: 15px;
  padding: 10px;
  background: #f4f4f5;
  border-radius: 4px;
}

.total-label {
  font-weight: 600;
  margin-right: 20px;
}

.total-amount {
  font-size: 18px;
  color: #f56c6c;
  font-weight: bold;
}
.validation-info {
  margin: 15px 0;
  padding: 10px;
  background: #f8f9fa;
  border-radius: 4px;
}

.amount-summary {
  margin-top: 10px;
  color: #606266;
  font-size: 14px;
}

.el-alert {
  margin-bottom: 10px;
}
 </style>







